package com.fjwt.gz.service.activity.platform.acte018;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fjwt.gz.core.cache.RedisUtil;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.db.bo.ActivityAwardAndSettingBo;
import com.fjwt.gz.db.bo.ActivityAwardBO;
import com.fjwt.gz.db.bo.ActivityUserTimesBO;
import com.fjwt.gz.db.dto.FansActivityDTO;
import com.fjwt.gz.db.entity.ActivityAwardEntity;
import com.fjwt.gz.db.entity.AgentInfoEntity;
import com.fjwt.gz.db.entity.FansAuthEntity;
import com.fjwt.gz.db.vo.ActivityAwardVO;
import com.fjwt.gz.service.activity.BaseActivityDTO;
import com.fjwt.gz.service.activity.BaseActivityService;
import com.fjwt.gz.service.impl.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class ACTE018Service extends BaseActivityService<Object> {

    @Autowired
    private FansAuthService fansAuthService;

    @Autowired
    private ActivitySettingService activitySettingService;

    @Autowired
    private ActivityAwardService activityAwardService;

    @Autowired
    private SendAwardService sendAwardService;

    @Autowired
    private AwardSettingService awardSettingService;

    @Autowired
    private FansAwardService fansAwardService;

    private static String logPrefix = "【拉新有礼活动】";
    @Autowired
    private AgentInfoService agentInfoService;

    /**
     * 删除活动
     */
    @Override
    public void delete(Long activityId) {
        log.info("删除ACTE018的活动");
        super.delete(activityId);
    }

    /**
     * 新建活动
     */
    @Override
    public void add(BaseActivityDTO activityDTO) {
        log.info("新增ACTE018的活动");
        super.add(activityDTO);
    }

    /**
     * 修改活动
     */
    @Override
    public void update(BaseActivityDTO activityDTO) {
        log.info("更新ACTE018的活动");
        super.update(activityDTO);
    }

    /**
     * 活动详情--pc
     */
    @Override
    public BaseActivityDTO detail(Long activityId) {
        log.info("查看ACTE018的活动详情");
        BaseActivityDTO baseActivityDetailsVO = super.detail(activityId);
        return baseActivityDetailsVO;
    }

    @Override
    public ActivityAwardVO takePartIn(FansActivityDTO fansActivityDTO) {
        log.info("进入拉新有礼活动");
        super.takePartIn(fansActivityDTO);
        Long activityChannelId = JSONUtil.parseObj(fansActivityDTO.getExtJson()).getLong("activityChannelId");

        // 判断是否实名
        LambdaQueryWrapper<FansAuthEntity> fansAuthEntityGw = FansAuthEntity.gw();
        fansAuthEntityGw.eq(FansAuthEntity::getAgentNo, fansActivityDTO.getAgentNo());
        fansAuthEntityGw.eq(FansAuthEntity::getFansId, fansActivityDTO.getFansId());
        List<FansAuthEntity> fansAuthEntityList = fansAuthService.list(fansAuthEntityGw);
        // 用户已实名
        if (ObjectUtil.isNotEmpty(fansAuthEntityList) && fansAuthEntityList.size() == 1){
            throw new BizException("您已是郑州邮政实名会员，请前往“郑邮享”小程序，享受更多会员权益。");
        }

        // 检测用户参与限制条件
        JSONObject jsonObject = activitySettingService.checkActivitySetting(fansEntity, fansActivityDTO.getAppId(), redisOutTime, activityEntity);

        // 判断用户是否参与过同类型的实名认证活动
        boolean isJoinRealNameAuth = fansAwardService.isJoinRealNameAuth(fansActivityDTO.getFansId(), fansActivityDTO.getLocationAgentNo());
        if (isJoinRealNameAuth) {
            throw new BizException("您已参加过同类型的实名认证活动");
        }

        // 检测活动奖品配置
        String activityAwardKey = String.format("%s%s:%s", Constants.REDIS_ACTIVITY.FILENAME, fansActivityDTO.getActivityId(), Constants.REDIS_ACTIVITY.AWARD);
        log.info("活动奖品列表redisKey:{}", activityAwardKey);
        List<ActivityAwardEntity> activityAwardList = RedisUtil.getObject(activityAwardKey, new TypeReference<List<ActivityAwardEntity>>() {
        });
        if (activityAwardList == null) {
            LambdaQueryWrapper<ActivityAwardEntity> activityAwardWrapper = new LambdaQueryWrapper<>();
            activityAwardWrapper.eq(ActivityAwardEntity::getActivityId, fansActivityDTO.getActivityId());
            activityAwardList = activityAwardService.list(activityAwardWrapper);
            if (activityAwardList != null && !activityAwardList.isEmpty()) {
                RedisUtil.set(activityAwardKey, activityAwardList, redisOutTime, TimeUnit.MILLISECONDS);
                log.info("活动奖品列表，从数据库加载到redis缓存中，redisKey:{},redisValue:{},redisOutTime:{},TimeUnit:{}", activityAwardKey, JSONUtil.toJsonStr(activityAwardList), redisOutTime, "TimeUnit.MILLISECONDS");
            }
        } else {
            log.info("活动奖品列表，redis缓存，redisKey:{},redisValue:{},redisOutTime:{},TimeUnit:{}", activityAwardKey, JSONUtil.toJsonStr(activityAwardList), redisOutTime, "TimeUnit.MILLISECONDS");
        }

        if (activityAwardList == null || activityAwardList.isEmpty()) {
            throw new BizException("活动奖品配置信息有误");
        }

        AgentInfoEntity agentInfoEntity = agentInfoService.getAgentInfo(fansActivityDTO.getLocationAgentNo());

        List<ActivityAwardAndSettingBo> awardAndSettingBos = awardSettingService.getActivityAwardList(fansActivityDTO.getActivityId(), redisOutTime);
        List<ActivityAwardBO> activityAwardBOList = activityAwardService.getAwardList(awardAndSettingBos);
        ActivityAwardBO activityAwardBO = activityAwardBOList.get(0);
        log.info("活动奖品详细信息:{}", JSONUtil.toJsonStr(activityAwardBO));
        long fansAwardId = sendAwardService.sendActivateAward(fansActivityDTO.getFansId(), fansActivityDTO.getAppId(), activityAwardBO.getAwardId(),
                Constants.AWARD.COUPON, activityEntity.getEndTime(), logPrefix, activityChannelId, Constants.FANS_AWARD_TAG.REAL_NAME_AUTH,
                "{\"templateNo\":\"ACTE018\"}", agentInfoEntity);
        activityAwardBO.setFansAwardId(fansAwardId);

        //更新Redis中参与的次数
        ActivityUserTimesBO activityUserTimesBO = jsonObject.getObject("activityUserTimesBO", ActivityUserTimesBO.class);
        if (ObjectUtils.isNotEmpty(activityUserTimesBO)) {
            activitySettingService.updateRedisParticipateNum(jsonObject.getString("currentTimesKey"), activityUserTimesBO, redisOutTime);
        }
        Boolean userJoinScoreValue = jsonObject.getObject("userJoinScoreValue", Boolean.class);
        if (ObjectUtils.isNotEmpty(userJoinScoreValue)){
            RedisUtil.set(jsonObject.getString("userJoinScoreKey"), userJoinScoreValue, redisOutTime, TimeUnit.MILLISECONDS);
        }
        return activityAwardService.toUserData(activityAwardBO);
    }
}
